# coding: utf8
from flask import current_app
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from app.constant import APP_CURRENT_TOKEN_KEY
from app.op.models import User


class AuthToken(object):
    """
    create by chenhj 2017-03-29
    auth token的生成和解析工具
    """
    @classmethod
    def generate_auth_token(cls, expiration, user):
        """
        create by zhouhl 2017-02-08
        使用用户id生成签名令牌
        @:param user: 用户
        """
        s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
        data = {
            'id': user.id,
        }
        token = s.dumps(data).decode('ascii')

        return token

    @classmethod
    def verify_auth_token(cls, token):
        """
        create by zhouhl 2017-02-08
        验证签名令牌
        """
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return None

        return User.get_by_id(data['id'])

    @classmethod
    def generate_app_token(cls, expiration, user):
        """
        create by ld_wu 2017-12-14
        获取app token
        同时写入redis做单设备登录管理及token管理
        """
        token = cls.generate_auth_token(expiration, user)
        current_app.redis.set(
            APP_CURRENT_TOKEN_KEY.format(user_id=user.id),
            token
        )
        return token

    @classmethod
    def verify_app_token(cls, token):
        """
        验证app token
        """
        user = cls.verify_auth_token(token)
        if user:
            current_token = current_app.redis.get(
                APP_CURRENT_TOKEN_KEY.format(user_id=user.id)
            )

            if current_token == token:
                return user
